# from tools.text_to_image import main
# # from tools.send_to import main
#
# main()
import numpy as np
from tools.lol.text_to_image import text_to_image
from tools.lol.text_to_image import image_dir
# image_path = os.path.join(image_dir, '不开心.png')
# image_path = os.path.join(image_dir, '问号.png')
# image_path = os.path.join(image_dir, '中指.png')
# image_path = os.path.join(image_dir, '花.png')
# image_path = os.path.join(image_dir, '笑脸.png')
# image_path = os.path.join(image_dir, 'QQ.png')
# image_path = os.path.join(image_dir, '火箭.png')
# text_to_image(image_path=image_path, font_size=16, threshold=254)
# text_to_image(image_path=image_path, font_size=11, threshold=205)

import gradio as gr

import os, asyncio

import tkinter as tk
from tkinter.filedialog import askopenfilename
import contextvars
import functools


def tk_window_asksavefile(init_dir=os.getcwd(), suffix='') -> str:
    window = tk.Tk()
    window.wm_attributes('-topmost', 1)
    window.withdraw()
    filename = askopenfilename(initialdir=init_dir, filetypes=[('', suffix)])
    return filename


async def to_thread(func, /, *args, **kwargs):
    loop = asyncio.get_running_loop()
    ctx = contextvars.copy_context()
    func_call = functools.partial(ctx.run, func, *args, **kwargs)
    return await loop.run_in_executor(None, func_call)


asyncio.to_thread = to_thread


async def tk_asksavefile_asy(init_dir=os.getcwd(), suffix='') -> str:
    fname = await asyncio.to_thread(tk_window_asksavefile, init_dir, suffix)
    return fname, fname


def greet(text):
    if not text:
        return 'Error: `text`不能为空!'

    text = text.replace("；", ';')
    if ';' in text:
        text = text.split(';')

    str_ls = []
    for t in text:
        if not t:
            continue
        _str_ls, _ = text_to_image(t)
        ss = '\n'.join([''.join(ls) for ls in _str_ls])
        str_ls.append(ss)

    res = '\n'.join(str_ls)
    return res


def conv_image_to_pixel_style(image):
    # return image.rotate(45)

    # image_path = os.path.join(image_dir, '火箭.png')
    # text_to_image(image_path=image_path, font_size=16, threshold=254)
    print(image)
    image.path

    return 123


def flip_image(x):
    return np.fliplr(x)


with gr.Blocks() as demo:
    # # 创建一个用于翻转文本的选项卡，包含一个文本输入框、一个文本输出框和一个按钮
    # with gr.Tab("Flip Text"):
    #     with gr.Row():
    #         with gr.Column(scale=2):
    #         # with gr.Column():
    #             gr.Markdown("输入文字转像素字")
    #             text = gr.Textbox(label="Name")
    #         output = gr.Textbox(label="Output Box", show_copy_button=True)
    #
    # # 创建一个用于翻转图片的选项卡，包含一个图片输入框、一个图片输出框和一个按钮
    # # 创建一个用于翻转图片的选项卡，包含一个图片输入框、一个图片输出框和一个按钮
    # with gr.Tab("Flip Image"):
    #     with gr.Row():
    #         image_input = gr.Image()
    #         # image_output = gr.Textbox(label="Output Box", show_copy_button=True)
    #         image_output = gr.Image()
    #     image_button = gr.Button("Flip")
    #
    # with gr.Accordion("Open for More!"):
    #     gr.Markdown("Look at me...")
    #
    # # text_button.click(flip_text, inputs=text_input, outputs=text_output)
    # image_button.click(flip_image, inputs=image_input, outputs=image_output)
    #
    # greet_btn = gr.Button("生成")
    # greet_btn.click(fn=greet, inputs=text, outputs=output, api_name="greet")

    examples = [os.path.join(image_dir, img_name) for img_name in os.listdir(image_dir)]

    with gr.Tab("Select Image"):
        norm_input_text = gr.Text(label='Input tif for normalization')
        # norm_input_text = gr.Dropdown(
        #     ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
        # ),
        # norm_input_img = gr.Image(type="pil")
        norm_input_img = gr.Image(height=400, width=400)
        norm_input_btn = gr.Button('Select input tif')

    # norm_input_btn.click(tk_asksavefile_asy, inputs=[], outputs=[norm_input_text, norm_input_img])

    def receiver_1(number, text):
        return number, text

    def receiver_2(image_path, image):
        if not image:
            image = image_path
        return image_path, image

    # gr.Interface(
    #     receiver_1,
    #     inputs=[
    #         gr.Dropdown(
    #             examples, label="示例图片", info="选择你想转化的图片!"
    #         ),
    #     ],
    #     outputs=[norm_input_text, norm_input_img]
    # )

    examples_2 = zip(examples, examples)

    gr.Interface(
        receiver_2,
        inputs=[
            gr.Dropdown(
                examples, label="示例图片", info="选择你想转化的图片!"
            ),
        ],
        outputs=[norm_input_text, norm_input_img],
        examples=examples,
    )

    # image_demo = gr.Interface(
    #     conv_image_to_pixel_style,
    #     gr.Image(type="pil"),
    #     # "image",
    #     outputs="image",
    #     flagging_options=["blurry", "incorrect", "other"],
    #     # examples=examples,
    #     examples=examples_2,
    #     # examples=[
    #     #     # os.path.join(image_dir, 'QQ.png'),
    #     #     # os.path.join(os.path.dirname(__file__), "images/cheetah1.jpg"),
    #     #     # os.path.join(os.path.dirname(__file__), "images/lion.jpg"),
    #     #     # os.path.join(os.path.dirname(__file__), "images/logo.png"),
    #     #     # os.path.join(os.path.dirname(__file__), "images/tower.jpg"),
    #     # ],
    # )

# demo.launch(inbrowser=True, server_name='0.0.0.0', server_port=7861)
demo.launch()


